package com.request.service.impl.shop.hf;

import cn.hutool.core.bean.BeanUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.request.common.constants.RedisConstant;
import com.request.common.enums.HfErrorCodeEnum;
import com.request.common.enums.SignTypeEnum;
import com.request.common.utils.HttpUtils;
import com.request.common.utils.SignUtils;
import com.request.entity.PhoneOrderAvailable;
import com.request.entity.PhoneOrderWaitPush;
import com.request.entity.out.PushOrderForHf;
import com.request.service.PushOrderProcessor;
import com.request.service.RedisService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.text.DecimalFormat;
import java.util.Map;
import java.util.TreeMap;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

/**
 * Description:
 * Create DateTime: 2020/5/22 10:53
 *
 * 

 */
@Slf4j
@Service
public class HfPushOrderProcessor implements PushOrderProcessor {

    @Resource
    private RedisService redisService;

    @Resource
    private ThreadPoolExecutor handlerOrderExecutor;

    @Resource
    private RedisTemplate<String, String> redisTemplate;

    @Override
    public void sendRequest(PhoneOrderWaitPush phoneOrderWaitPush) {
        handlerOrderExecutor.execute(() -> executeSend(phoneOrderWaitPush));
    }

    private void executeSend(PhoneOrderWaitPush phoneOrderWaitPush) {
        if (phoneOrderWaitPush == null) {
            return;
        }
        PhoneOrderAvailable phoneOrderAvailable = phoneOrderWaitPush.getPhoneOrderAvailable();
        PushOrderForHf pushOrderForHf = new PushOrderForHf();

        String result = null;
        try {
            //组装参数
            pushOrderForHf.setApi_code(phoneOrderWaitPush.getAppId());
            pushOrderForHf.setOrig_price(formatBigDecimal(phoneOrderAvailable.getOrderPrice()));
            pushOrderForHf.setCpparam(phoneOrderAvailable.getPlatformOrderNo());
            pushOrderForHf.setCburl(phoneOrderWaitPush.getShopCallbackSite());
            pushOrderForHf.setPhonenum(phoneOrderAvailable.getPhoneNum());
            pushOrderForHf.setCarrier(Integer.valueOf(phoneOrderAvailable.getPhoneOperator()));
            pushOrderForHf.setExpire(phoneOrderAvailable.getOrderExpireTime());

            //生成签名
            TreeMap<String, String> signMap = new TreeMap<>();
            signMap.put("a", phoneOrderWaitPush.getAppKey());
            signMap.put("b", pushOrderForHf.getCpparam());
            signMap.put("c", pushOrderForHf.getPhonenum());
            signMap.put("d", formatBigDecimal(pushOrderForHf.getOrig_price()).toPlainString());
            signMap.put("e", pushOrderForHf.getCarrier().toString());
            signMap.put("f", phoneOrderWaitPush.getShopCallbackSite());
            signMap.put("g", phoneOrderWaitPush.getAppKey());

            String sign = SignUtils.generateSignature(signMap, SignTypeEnum.MD5);
            pushOrderForHf.setSign(sign);

            try {
                result = sendRequestForPushOrder(phoneOrderWaitPush.getPushSite(), pushOrderForHf);
            } catch (Exception e) {
                savePushOrderForException(phoneOrderWaitPush);
                savePushOrderForSuccess(phoneOrderAvailable.getPlatformOrderNo());
                log.info("【Hf】【推单】发送请求出现异常：", e);
                return;
            }

            log.info("【Hf】【推单】订单号为：{}, 结果:{}", phoneOrderAvailable.getPlatformOrderNo(), result);
            JSONObject json = JSONObject.parseObject(result);
            String code = json.getString("code");

            if (HfErrorCodeEnum.FAIL.getCode().equals(code)) {
                log.info("【Hf】【推单】响应状态失败,状态为：{}", code);
                savePushOrderForFailed(phoneOrderWaitPush);
                return;
            }
            if (!HfErrorCodeEnum.SUCCESS.getCode().equals(code)) {
                String msg = json.getString("msg");
                throw new RuntimeException("推送订单商户相应失败，相应的状态码为 : "+ code + ",对应的信息为 : " + msg + ",订单号为：{}" + phoneOrderAvailable.getPlatformOrderNo());
            }
            savePushOrderForSuccess(phoneOrderAvailable.getPlatformOrderNo());
        } catch (Exception e) {
            //savePushOrderForFailed(phoneOrderWaitPush);
            savePushOrderForSuccess(phoneOrderAvailable.getPlatformOrderNo());
            log.error("【Hf】【推送订单】推送订单失败，待推送订单信息为：{}, 请求参数为：{}, 商户响应结果为：{}, 详细错误信息为：",
                    phoneOrderWaitPush, pushOrderForHf, result, e);
        }
    }

    //保留orderPrice小数点两位（例如100格式化为100.00）
    private BigDecimal formatBigDecimal(BigDecimal orderPrice){
        DecimalFormat decimalFormat = new DecimalFormat("#.00");
        String format = decimalFormat.format(orderPrice);
        BigDecimal formatOrderPrice = new BigDecimal(format);
        return formatOrderPrice;
    };

    /**
     * 放入失败队列
     */
    private void savePushOrderForFailed(PhoneOrderWaitPush phoneOrderWaitPush) {
        redisService.lPush(RedisConstant.PUSH_ORDER_WAIT_PUSH_RECORD, JSON.toJSONString(phoneOrderWaitPush));
    }

    /**
     * 放入成功队列
     */
    private void savePushOrderForSuccess(String platformOrderNo) {
        redisTemplate.opsForValue().set(RedisConstant.PUSH_ORDER_WAIT_PUSH_SUCCESS + platformOrderNo, platformOrderNo, 30, TimeUnit.MINUTES);
    }

    /**
     * 发送Http请求
     *
     * @param url    请求路径
     * @param pushOrderForHf  参数
     * @return 响应结果
     */
    private String sendRequestForPushOrder(String url, PushOrderForHf pushOrderForHf) {
        Map<String, Object> paramMap = BeanUtil.beanToMap(pushOrderForHf);
        return HttpUtils.doPost(url, paramMap);
    }

    /**
     * 放入发送出现异常的队列
     */
    private void savePushOrderForException(PhoneOrderWaitPush phoneOrderWaitPush) {
        redisService.lPush(RedisConstant.PUSH_ORDER_WAIT_PUSH_EXCEPTION, JSON.toJSONString(phoneOrderWaitPush));
    }
}
